import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		// 用户登录成功或者用户拒绝登录
		hasLogin: true,
		// 登录提交信息安全Key，加密用户名、密码、验证码，后再提交（key设置为3个，用逗号分隔）
		secretKey: 'thinkgem,jeesite,com',
		//HOST_URL: 'http://demo.jeesite.com/js',
		HOST_URL: 'http://192.168.0.113:8981/pid',
		// 存储sessionId
		sessionId: null,
		// 定义公共变量
		GLOBEL_TRUE: "true",
		// 用户信息
		user:{},
		// 角色信息
		roles:[],
		// 权限信息
		stringPermissions:[]
	},
	mutations: {
		// 用户拒绝登录(点取消按钮)
		loginFail(state) {
			state.hasLogin = false
		},
		userCancel(state, openid) {
			state.hasLogin = true
		}
	},
	actions: {
		// 自动登录 包括登录超时的统一处理
		autoLogin: function({
			commit,
			state,
			dispatch
		}, fun) {
			// 开始自动登录
			return new Promise((resolve, reject) => {
				uni.showLoading({
					title: "登陆中"
				})
				uni.getStorage({
					key: 'jeesite_user',
					success: function(res) {
						let {
							username,
							password
						} = res.data;
						uni.request({
							url: state.HOST_URL + '/a/login?__login=true&__ajax=json&username=' + username + "&password=" +
								password + "&param_deviceType=mobileApp&t=" + new Date().getTime(),
							success: (data) => {
								console.log("success")
								uni.hideLoading();
								if (data && data.statusCode == 200) {
									setTimeout(function() {
										uni.showToast({
											title: data.data.message,
											icon: "none"
										})
									}, 200);
									if (data && data.data.result == state.GLOBEL_TRUE) {
										state.sessionId = data.data.sessionid;
										state.hasLogin = true;
										state.user = data.data.user;
										state.user.avatarUrl = state.HOST_URL + data.data.user.avatarUrl.toString().replace("/ctxPath","");
										console.log("登录成功")
										dispatch("authInfo");
									} else {
										state.hasLogin = false;
									}
								} else {
									state.hasLogin = false;
									setTimeout(function() {
										uni.showToast({
											title: '网络出错',
											icon: "none"
										})
									}, 200);
								}
								resolve();
							},
							fail: (data, code) => {
								uni.hideLoading();
								state.hasLogin = false;
								setTimeout(function() {
									uni.showToast({
										title: '网络出错',
										icon: "none"
									})
								}, 200);
								console.log('fail' + JSON.stringify(data));
								reject()
							},
						})
					}
				});
			})
		},
		// 刷新角色权限信息
		authInfo: function({
			commit,
			state,
			dispatch
		}, fun) {
			return new Promise((resolve, reject) => {
				uni.request({
					url: state.HOST_URL + '/a/authInfo?__ajax=json' + "&__sid=" + state.sessionId + "&t=" + new Date().getTime(),
					success: (data) => {	
						console.log(data)
						state.roles = data.data.roles;
						state.stringPermissions = data.data.stringPermissions;
						console.log(state.roles);
						console.log(state.stringPermissions);
						resolve()
					},
					fail: (data, code) => {
						uni.hideLoading();
						state.hasLogin = false;
						setTimeout(function() {
							uni.showToast({
								title: '网络出错',
								icon: "none"
							})
						}, 200);
						console.log('fail' + JSON.stringify(data));
						reject()
					},
				})
			})
		},
		// 获取字典信息
		JgetDic: function({
			commit,
			state,
			dispatch
		}, dicValue) {
			return new Promise((resolve, reject) => {
				uni.request({
					url: state.HOST_URL + '/a/sys/dictData/listData?dictType='+dicValue+'&__ajax=json' + "&__sid=" + state.sessionId + "&t=" + new Date().getTime(),
					success: (data) => {	
						resolve(data);
					},
					fail: (data, code) => {
						uni.hideLoading();
						state.hasLogin = false;
						setTimeout(function() {
							uni.showToast({
								title: '网络出错',
								icon: "none"
							})
						}, 200);
						console.log('fail' + JSON.stringify(data));
						reject()
					},
				})
			})
		},
		// 统一AJAX请求 
		// 1.登录超时时自动登录
		// 2.网络错误时 非200的情况提示【网络出错，是否重新加载】
		JAjax: async function({
			state,
			commit,
			dispatch
		}, para) {
			uni.request({
				url: state.HOST_URL + (para.url.indexOf("?") == -1 ? para.url + "?" : para.url) + '&t=' + new Date().getTime() +
					'&__sid=' +
					state.sessionId + "&__ajax=json",
				data: para.data,
				method:para.method || "GET",
				header: para.header || {},
				success: (data) => {
					// 如果登录超时自动重新登录
					if(data && data.data.result == "login"){
						dispatch("autoLogin", para).then(function(){
							dispatch("JAjax", para);
						}),function(){
							uni.showModal({
								title: '系统错误',
								content: "是否重新加载",
								showCancel: true,
								success: function(res) {
									if (res.confirm) {
										dispatch("JAjax", para);
									}
								}
							});
						};
					}
					// 权限是否足够
					if(data.statusCode == 403){
						uni.showToast({
							title: '权限不足',
							icon:"none"
						});
					}
					para.success(data);
				},
				fail: (data, code) => {
					uni.hideLoading();
					console.log("fail")
					uni.showModal({
						title: '网络错误',
						content: "是否重新加载",
						showCancel: true,
						success: function(res) {
							if (res.confirm) {
								dispatch("JAjax", para);
							}
						}
					});
				},
			})
		}
	}
})

export default store